import { PrismaService } from '@app/prisma';
import { Body, Controller, ForbiddenException, Get, Post, UseGuards } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LoginInput } from './dto/login.input';
import { HashService } from '@app/hash';
import { CurrentUser, JwtAuthGuard } from './auth.guard';
import { UserEntity } from '@app/prisma/user.entity/user.entity';
import { ApiBody, ApiOperation, ApiTags } from '@nestjs/swagger';

@Controller('auth')
@ApiTags("登录接口")
export class AuthController {
    constructor(
        private readonly prisma: PrismaService,
        private readonly authService: AuthService,
        private readonly hashService: HashService
    ) { }


    @Post("login")
    @ApiOperation({ description: "用户登录" })
    async login(
        @Body() { account, password }: LoginInput
    ) {
        const user = await this.prisma.user.findUnique({
            where: {
                account
            },
            include: {
                profile: true
            }
        })
        if (!user) throw new ForbiddenException("找不到用户")
        if (this.hashService.cryptoPassword(password) !== user.profile.password) {
            throw new ForbiddenException("密码错误")
        }
        return this.authService.getToken(user);
    }

    @Get("viewer")
    @ApiOperation({ description: "获取登录信息" })
    @UseGuards(JwtAuthGuard)
    async viewer(
        @CurrentUser() user: UserEntity
    ) {
        return user;
    }
}
